from flask import Flask, make_response
from flask import Flask, request, jsonify
from pydantic import ValidationError

from cfganalysis.DUPathCollector import generate_dupath_json
from cfganalysis.ProgramAnalysis import generate_cfg, generate_cfg_with_gpt, generate_dupath_with_gpt, \
    generate_cfg_with_astandgpt
from cfganalysis.cfg_builder import generate_cfg_json
from utils.parseData import response_json, preprocess_macros

app = Flask(__name__)

@app.errorhandler(404)
def not_found_error(error):
    return response_json(404, "Resource not found")

@app.errorhandler(500)
def internal_error(error):
    return response_json(500, "Internal server error")
@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'
@app.after_request
def after(resp):
    '''
    被after_request钩子函数装饰过的视图函数
    ，会在请求得到响应后返回给用户前调用，也就是说，这个时候，
    请求已经被app.route装饰的函数响应过了，已经形成了response，这个时
    候我们可以对response进行一些列操作，我们在这个钩子函数中添加headers，所有的url跨域请求都会允许！！！
    '''
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp

# @app.route('/normalcfg', methods=['POST'])
# def generate_cfg():
#     data = request.json
#     code = data.get("code", "")
#     if not data or 'code' not in data:
#         response_json(514, "代码不能为空")  # 返回验证错误
#
#     try:
#         return generate_cfg_json(code)
#
#     except Exception as e:
#         return response_json(503, str(e))  # 返回验证错误


@app.route("/analyzecfg", methods=["POST"])
def analyzecfg_code():
    # 从请求中获取 JSON 数据
    try:
        data = request.json
        code = data.get("code", "")
        preprocessed_code = preprocess_macros(code)
        print(preprocessed_code)
        language = data.get("language", "")
        mode = data.get("mode","AI")
        model = data.get("model", "gpt-3.5-turbo")
        if not code:
            response_json(514, "代码不能为空")  # 返回验证错误\
        if mode == "AI":
            return generate_cfg_with_gpt(code,language,model)
        elif mode == "Normal":
            return generate_cfg_json(preprocessed_code)
        else:
            return generate_cfg_with_astandgpt(preprocessed_code,language,model)
        # return response_json(514,"不受支持的语言")
    except (ValidationError, TypeError) as e:
        return response_json(503, str(e))# 返回验证错误

@app.route("/analyzedu", methods=["POST"])
def analyzedu_code():

    # 从请求中获取 JSON 数据
    try:
        data = request.json
        code = data.get("code", "")
        preprocessed_code = preprocess_macros(code)
        print(preprocessed_code)
        language = data.get("language", "")
        mode = data.get("mode", "AI")
        model = data.get("model", "gpt-3.5-turbo")
        if not code:
            response_json(514, "代码不能为空")  # 返回验证错误
        if mode == "AI":
            return generate_dupath_with_gpt(code,language,model)
        else:
            return generate_dupath_json(preprocessed_code)
        # return response_json(514,"不受支持的语言")
    except (ValidationError, TypeError) as e:
        return response_json(503, str(e))# 返回验证错误





if __name__ == '__main__':
    app.run()
